﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PessModel;
using System.Web.Security;
using PessMvc.Models;
using System.Configuration;
using System.Web.Profile;
using PessMvc.Helpers;
using System.IO;
using System.Web.Script.Serialization;

namespace PessMvc.Controllers
{
    [Authorize(Roles="Author")]
    [NotNeedToChangePassword]
    public class AuthorController : Controller
    {
        private PESSEntities db = new PESSEntities();

        public ActionResult Index()
        {
            if (!string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["CurrentActivityID"]))
            {
                int caid = int.Parse(ConfigurationManager.AppSettings["CurrentActivityID"]);
                if (db.Activities.Find(caid) != null)
                {
                    HttpContext.Session.Add("ActivityID", caid);
                }
            }
            return View();
        }

        

        public ActionResult Proposals()
        {
            ArchivesModel model;
            MembershipUser user=Membership.GetUser();
            Guid? authorUserID=new Guid(user.ProviderUserKey.ToString());
            var archives = db.Archives.Where(a => (a.UserID == authorUserID || a.PAuthors.Select(p => p.EMail).Contains(user.Email)) && a.Status > 1).OrderBy(a=>a.Status);//hide deleted proposals.
            //archives.Where(a => a.PaperStatus == 3 || a.PaperStatus == 4).Select(a => a.PaperStatus = 2);
            foreach(Archive a in archives)
            {
                if(a.PaperStatus == 3 || a.PaperStatus == 4)
                {
                    a.PaperStatus = 2;
                }
            }
            
            model = new ArchivesModel(archives.ToList());
             int caid = int.Parse(ConfigurationManager.AppSettings["CurrentActivityID"]);
             Activity activity = db.Activities.Find(caid);
            ViewBag.IsArchiveModificationAllowed = Utility.IsArchiveModificationAllowed(activity, new ModelStateDictionary());
            ViewBag.IsPaperUploadAllowed=Utility.IsPaperUploadAllowed(activity, new ModelStateDictionary());
            return View(model);
        }

        public ActionResult ChooseActivity()
        {
            return View(db.Activities);
        }

        [ArchiveSubmssionAllowed]
        public ActionResult CreateProposal()
        {
            int activityID = -1;
            if (!string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["CurrentActivityID"]))
            {
                activityID = int.Parse(ConfigurationManager.AppSettings["CurrentActivityID"]);
            }
            Activity activity = db.Activities.Find(activityID);

            ViewBag.ActivityID = activityID;
            var counties = (from c in db.Counties
                           join q in db.CandidateQuotas on c.Code equals q.CountyCode
                           where q.Subject.ActivityID == activityID
                           select c).Distinct();
            ViewBag.CountyCode = new SelectList(counties, "Code", "Name");
            ViewBag.Tracks = new SelectList(db.Tracks.Where(t => t.ActivityID == activityID), "ID", "Title");
            //ViewBag.SubjectID = new SelectList(db.Subjects.Where(s=>s.ActivityID==activityID), "ID", "Name");           

            
            ProfileBase profile = ProfileBase.Create(Membership.GetUser().UserName);
            Archive model = new Archive();
            model.FirstName = profile["FirstName"] == null ? "" : profile["FirstName"].ToString();
            model.LastName = profile["LastName"] == null ? "" : profile["LastName"].ToString();
            model.PhoneNumber = profile["PhoneNumber"] == null ? "" : profile["PhoneNumber"].ToString();
            model.SchoolName = profile["Organization"] == null ? "" : profile["Organization"].ToString();
            model.ZipCode = profile["ZipCode"] == null ? "" : profile["ZipCode"].ToString();
            model.StateProvince = profile["StateProvince"] == null ? "" : profile["StateProvince"].ToString();
            model.Country = profile["Country"] == null ? "" : profile["Country"].ToString();
            model.City = profile["City"] == null ? "" : profile["City"].ToString();
            model.Address1 = profile["Address1"] == null ? "" : profile["Address1"].ToString();
            model.Address2 = profile["Address2"] == null ? "" : profile["Address2"].ToString();
            model.ProfessionalTitle=profile["ProfessionalTitle"] == null ? "" : profile["ProfessionalTitle"].ToString();
            model.FAX = profile["Fax"] == null ? "" : profile["Fax"].ToString();
            model.EMail = Membership.GetUser().Email;
            model.GradeLevel = ConfigurationManager.AppSettings["currentround"];

            if (activity.TypeID == 2)
            {
                model.Gender = true;
                ViewBag.CountyCode = new SelectList(counties.Where(c => c.Code == "04"), "Code", "Name");
            }
            else
            {
                model.Gender = false;
            }

            return View(model);
        }

        [HttpPost]
        //[ValidateAntiForgeryToken]
        [ArchiveSubmssionAllowed]
        public ActionResult CreateProposal(Archive archive)//, int SubjectID)
        {
            if (ModelState.IsValid)
            {
                //archive.CountyCode="BS";
                //archive.SubjectID = SubjectID;
                archive.SuggestedCategory = archive.CountyCode;
                archive.UserID = new Guid(Membership.GetUser().ProviderUserKey.ToString());
                archive.Status = (int)ArchiveStatus.Cancelled;
                archive.SchoolComment = archive.SchoolComment.Replace("<", "&lt;").Replace(">", "&gt;").Replace("&lt;br/&gt;", "").Replace("\n", "<br/>");
                archive.CountyEBComment = archive.CountyEBComment.Replace("<", "&lt;").Replace(">", "&gt;").Replace("&lt;br/&gt;", "").Replace("\n", "<br/>");
                //archive.EditorPaperReviewFeedback = archive.EditorPaperReviewFeedback.Replace("<", "&lt;").Replace(">", "&gt;").Replace("&lt;br/&gt;", "").Replace("\n", "<br/>");
                //archive.ChairProposalFeedBack = archive.ChairProposalFeedBack.Replace("<", "&lt;").Replace(">", "&gt;").Replace("&lt;br/&gt;", "").Replace("\n", "<br/>");
                //archive.ReviewFeedback = archive.ReviewFeedback.Replace("<", "&lt;").Replace(">", "&gt;").Replace("&lt;br/&gt;", "").Replace("\n", "<br/>");
                //Activity activity = db.Activities.Find(archive.Subject.ActivityID);
                db.Archives.Add(archive);
                PAuthor pauthor = new PAuthor()
                {
                    ArchiveID = archive.ID,
                    EMail = archive.EMail,
                    Country = archive.Country,
                    FirstName = archive.FirstName,
                    LastName = archive.LastName,
                    Organization = archive.SchoolName,
                    Order = 1,
                    Type = archive.CountyCode == "01" ? 2 : 0
                };
                db.PAuthors.Add(pauthor);
                db.SaveChanges();
                //return RedirectToAction("Proposals", "Author", new { });

                return RedirectToAction("Index", "PAuthor", new { id = archive.ID });
            }

            //ViewBag.CountyCode = new SelectList(db.Counties, "Code", "Name", archive.CountyCode);
            //ViewBag.SubjectID = new SelectList(db.Subjects, "ID", "Name", archive.SubjectID);
            //ViewBag.ExpertGroupID = new SelectList(db.ExpertGroups, "ID", "LeaderID", archive.ExpertGroupID);
            int activityID = -1;
            if (!string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["CurrentActivityID"]))
            {
                activityID = int.Parse(ConfigurationManager.AppSettings["CurrentActivityID"]);
            }
            ViewBag.ActivityID = activityID;
            var counties = (from c in db.Counties
                            join q in db.CandidateQuotas on c.Code equals q.CountyCode
                            where q.Subject.ActivityID == activityID
                            select c).Distinct();
            ViewBag.CountyCode = new SelectList(counties, "Code", "Name");
            ViewBag.Tracks = new SelectList(db.Tracks.Where(t => t.ActivityID == activityID), "ID", "Title");
            //ViewBag.SubjectID = new SelectList(db.Subjects.Where(s=>s.ActivityID==activityID), "ID", "Name");           

            return View(archive);
        }

        [HttpGet]
        [ArchiveSubmssionAllowed]
        public JsonResult FinishNewProposal(int id)
        {
            Archive archive = db.Archives.Find(id);
            //security check
            if (!Utility.IsUserAllowedtoOpenArchive(archive, Membership.GetUser()))
                return Json(HttpContext.Request.Url.Scheme + "://" + HttpContext.Request.Url.Authority + Url.Action("Proposals", "Author"), JsonRequestBehavior.AllowGet);

            archive.Status = (int)ArchiveStatus.Submitted;
            db.Entry(archive).State = EntityState.Modified;
            db.SaveChanges();

           using (StreamReader reader = new StreamReader(Server.MapPath("~/App_Data/templates/proposalconfirm.txt")))
            {
                //string shortdescription = archive.SchoolComment.Replace("&lt;", "<").Replace("&gt;", ">").Replace("<br/>", "\n");
                //string text_abstract= archive.CountyEBComment.Replace("&lt;", "<").Replace("&gt;", ">").Replace("<br/>", "\n"); 
               string text = reader.ReadToEnd();
                text = text.Replace("[ProposalID]", archive.CalculatedSerialNumber);
                text = text.Replace("[ContactName]", archive.Name);
                text = text.Replace("[Date]", DateTime.Now.Date.ToString("MM/dd/yyyy"));
                text = text.Replace("[ContactTitle]", archive.ProfessionalTitle);
                text = text.Replace("[ContactAffiliation]", archive.SchoolName);
                text = text.Replace("[ContactAddress]", archive.ContactAddress);
                text = text.Replace("[ContactEmail]", archive.EMail);
                text = text.Replace("[ContactPhone]", archive.PhoneNumber);
                text = text.Replace("[ContactFax]", archive.FAX);
                text = text.Replace("[Title]", archive.ProjectTitle);
               // text = text.Replace("[ShortDescription]", shortdescription);
                //text = text.Replace("[Abstract]", text_abstract);
                text = text.Replace("[Track]", archive.Subject.Track.Title);
                text = text.Replace("[Topic]", archive.Subject.Name);
                text = text.Replace("[Format]", archive.County.Name);
                text = text.Replace("[TechRequirements]", archive.TechnologyRequirements);
                // text=text.Replace("[Authors]",);
                // text=text.Replace("[Topic]",);
                Utility.SendMail("Proposal Confirmation for " + archive.Name, text, archive.EMail);
            }
            //return RedirectToAction("Proposals");
            return Json(HttpContext.Request.Url.Scheme + "://" + HttpContext.Request.Url.Authority + Url.Action("Proposals", "Author"), JsonRequestBehavior.AllowGet);
        }

      

        //
        // GET: /Author/

        //public ActionResult Index()
        //{
        //    var archives = db.Archives.Include(a => a.County).Include(a => a.Subject).Include(a => a.ExpertGroup);
        //    return View(archives.ToList());
        //}

        //
        // GET: /Author/Details/5

        public ActionResult Details(int id = 0)
        {
            Archive archive = db.Archives.Find(id);
            //security check
            if (!Utility.IsUserAllowedtoOpenArchive(archive, Membership.GetUser()))
                return RedirectToAction("Proposals");


            Activity activity = archive.Subject.Activity;
            if (archive == null)
            {
                return HttpNotFound();
            }

            if(User.IsInRole("Author"))
            {
                if(archive.PaperStatus==3||archive.PaperStatus==4)
                {
                    archive.PaperStatus = 2;
                }
            }

            ViewBag.IsArchiveModificationAllowed = Utility.IsArchiveModificationAllowed(activity, new ModelStateDictionary());
            ViewBag.IsPaperUploadAllowed = Utility.IsPaperUploadAllowed(activity, new ModelStateDictionary());
            return View(archive);
        }

        //
        // GET: /Author/Create

        public ActionResult Create()
        {
            ViewBag.CountyCode = new SelectList(db.Counties, "Code", "Name");
            ViewBag.SubjectID = new SelectList(db.Subjects, "ID", "Name");
            ViewBag.ExpertGroupID = new SelectList(db.ExpertGroups, "ID", "LeaderID");
            return View();
        }

        //
        // POST: /Author/Create



        //
        // GET: /Author/Edit/5
        [ArchiveSubmssionAllowed]
        public ActionResult EditProposal(int id = 0)
        {
            Archive archive = db.Archives.Find(id);
            if (archive == null)
            {
                return HttpNotFound();
            }
            //security check
            if (!Utility.IsUserAllowedtoOpenArchive(archive, Membership.GetUser()))
                return RedirectToAction("Proposals");


            ViewBag.CountyCode = new SelectList(db.Counties, "Code", "Name", archive.CountyCode);
            ViewBag.SubjectID = new SelectList(db.Subjects.Where(s=>s.TrackID==archive.Subject.TrackID), "ID", "Name", archive.SubjectID);
            ViewBag.ExpertGroupID = new SelectList(db.ExpertGroups, "ID", "LeaderID", archive.ExpertGroupID);
            ViewBag.Tracks = new SelectList(db.Tracks.Where(t => t.ActivityID == archive.Subject.ActivityID), "ID", "Title",archive.Subject.TrackID);
            archive.SchoolComment = archive.SchoolComment.Replace("&lt;", "<").Replace("&gt;", ">").Replace("<br/>", "\n");
            archive.CountyEBComment = archive.CountyEBComment.Replace("&lt;", "<").Replace("&gt;", ">").Replace("<br/>", "\n");

            if(archive.Gender==true)//if gender is true, it is a virtual presentation
                ViewBag.CountyCode = new SelectList(db.Counties.Where(c => c.Code == "04"), "Code", "Name", archive.CountyCode);

            //archive.ChairProposalFeedBack = archive.ChairProposalFeedBack.Replace("&lt;", "<").Replace("&gt;", ">").Replace("<br/>", "\n");
            //archive.ReviewFeedback = archive.ReviewFeedback.Replace("&lt;", "<").Replace("&gt;", ">").Replace("<br/>", "\n");
            //archive.EditorPaperReviewFeedback = archive.EditorPaperReviewFeedback.Replace("&lt;", "<").Replace("&gt;", ">").Replace("<br/>", "\n");
            return View(archive);
        }

        //
        // POST: /Author/Edit/5

        [HttpPost]
        [ValidateAntiForgeryToken]
        [ArchiveSubmssionAllowed]
        public ActionResult EditProposal(Archive archive)
        {
            //security check
            if (!Utility.IsUserAllowedtoOpenArchive(archive, Membership.GetUser()))
                return RedirectToAction("Proposals");


            if (ModelState.IsValid)
            {
                archive.SchoolComment = archive.SchoolComment.Replace("<", "&lt;").Replace(">", "&gt;").Replace("&lt;br/&gt;", "").Replace("\n", "<br/>");
                archive.CountyEBComment = archive.CountyEBComment.Replace("<", "&lt;").Replace(">", "&gt;").Replace("&lt;br/&gt;", "").Replace("\n", "<br/>");
                //archive.EditorPaperReviewFeedback = archive.EditorPaperReviewFeedback.Replace("<", "&lt;").Replace(">", "&gt;").Replace("&lt;br/&gt;", "").Replace("\n", "<br/>");
                //archive.ChairProposalFeedBack = archive.ChairProposalFeedBack.Replace("<", "&lt;").Replace(">", "&gt;").Replace("&lt;br/&gt;", "").Replace("\n", "<br/>");
                //archive.ReviewFeedback = archive.ReviewFeedback.Replace("<", "&lt;").Replace(">", "&gt;").Replace("&lt;br/&gt;", "").Replace("\n", "<br/>");
                archive.SuggestedCategory = archive.CountyCode;
                db.Entry(archive).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Proposals");
            }
            ViewBag.CountyCode = new SelectList(db.Counties, "Code", "Name", archive.CountyCode);
            ViewBag.SubjectID = new SelectList(db.Subjects, "ID", "Name", archive.SubjectID);
            ViewBag.ExpertGroupID = new SelectList(db.ExpertGroups, "ID", "LeaderID", archive.ExpertGroupID);
            ViewBag.Tracks = new SelectList(db.Tracks.Where(t => t.ActivityID == archive.Subject.ActivityID), "ID", "Title");
            return View(archive);
        }

        //
        // GET: /Author/Delete/5

        public ActionResult Delete(int id = 0)
        {
            Archive archive = db.Archives.Find(id);
            //security check
            if (!Utility.IsUserAllowedtoOpenArchive(archive, Membership.GetUser()))
                return RedirectToAction("Proposals");

            if (archive == null)
            {
                return HttpNotFound();
            }
            return View(archive);
        }

        //
        // POST: /Author/Delete/5

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public JsonResult DeleteConfirmed(int id)
        {
            Archive archive = db.Archives.Find(id);
            //security check
            if (!Utility.IsUserAllowedtoOpenArchive(archive, Membership.GetUser()))
                //return RedirectToAction("Proposals");
                return Json(HttpContext.Request.Url.Scheme + "://" + HttpContext.Request.Url.Authority + Url.Action("Proposals"), JsonRequestBehavior.AllowGet);


            archive.Status = (int)ArchiveStatus.Cancelled;//not really delete, just marked as delete.
            db.SaveChanges();
            //return RedirectToAction("Proposals");
            return Json(HttpContext.Request.Url.Scheme + "://" + HttpContext.Request.Url.Authority + Url.Action("Proposals"), JsonRequestBehavior.AllowGet);
        }


        [HttpPost]
        [ArchiveSubmssionAllowed]
        public ActionResult SubmitProposal(int proposalID)
        {
            var archive = db.Archives.Find(proposalID);
            if (archive.UserID == new Guid(Membership.GetUser().ProviderUserKey.ToString()))
            {
                archive.Status =(int) ArchiveStatus.Submitted;
                db.SaveChanges();
            }
            return RedirectToAction("Proposals");
        }

        public ActionResult ReviewFeedback(int id)
        {
            Archive archive = db.Archives.Find(id);
            //security check
            if (!Utility.IsUserAllowedtoOpenArchive(archive, Membership.GetUser()))
                return RedirectToAction("Proposals");

            ArchiveReviewFeedbackModel model = new ArchiveReviewFeedbackModel();
            model.ProposalID = archive.CalculatedSerialNumber;
            model.ChairProposalFeedback = archive.ChairProposalFeedBack;
            model.ProposalTitle = archive.ProjectTitle;
            model.Status = archive.StatusName;
            model.AcceptedFormat = archive.County1.Name;
            model.Feedbacks = new List<ReviewerFeedbackModel>();
            var listec = db.ExpertComments.Where(ec => ec.ArchiveID == id);
            if (listec.Count() > 0)
            {
                foreach (var ec in listec)
                {
                    if (ec.AcceptanceStatus >= 0)
                    {
                        ReviewerFeedbackModel rf = new ReviewerFeedbackModel();
                        rf.ExpertSerialNumber = ec.ExpertSerialNumber;
                        rf.Acceptance = (AcceptanceStatus)ec.AcceptanceStatus;
                        rf.Comment = ec.Comment;
                        rf.Scores = new List<KeyValuePair<string, int>>();
                        var lstScore = db.Scores.Where(s => s.ArchiveID == id && s.ExpertJudgeSerialNumber == ec.ExpertSerialNumber);
                        if (lstScore.Count() > 0)
                        {
                            foreach(var s in lstScore)
                            {
                                rf.Scores.Add(new KeyValuePair<string, int>(s.Rule.Name, Convert.ToInt32(s.Value)));
                            }
                        }
                        model.Feedbacks.Add(rf);
                    }
                }
            }
            
            return View(model);
        }

        public ActionResult ReviewPaperFeedback(int id)
        {
            Archive archive = db.Archives.Find(id);
            //security check
            if (!Utility.IsUserAllowedtoOpenArchive(archive, Membership.GetUser()))
                return RedirectToAction("Proposals");


            //ArchivePaperReviewFeedbackModel model = new ArchivePaperReviewFeedbackModel();
            //model.ProposalID = archive.CalculatedSerialNumber;
            //model.ProposalTitle = archive.ProjectTitle;
            //model.Status = archive.PaperStatusName;
            //model.Feedbacks = new List<PaperReviewerFeedbackModel>();
            //var listec = db.PaperComments.Where(ec => ec.ArchiveID == id);
            //if (listec.Count() > 0)
            //{
            //    foreach (var ec in listec)
            //    {
            //        if (ec.PaperStatus >= 0)
            //        {
            //            PaperReviewerFeedbackModel rf = new PaperReviewerFeedbackModel();
            //            rf.ExpertSerialNumber = ec.ExpertSerialNumber;
            //            rf.Acceptance = (PaperAcceptanceStatus)ec.PaperStatus;
            //            rf.Comment = ec.Comment;
            //            rf.Scores = new List<KeyValuePair<string, int>>();
            //            var lstScore = db.PaperScores.Where(s => s.ArchiveID == id && s.ExpertJudgeSerialNumber == ec.ExpertSerialNumber);
            //            if (lstScore.Count() > 0)
            //            {
            //                foreach (var s in lstScore)
            //                {
            //                    rf.Scores.Add(new KeyValuePair<string, int>(s.PaperRule.Name, Convert.ToInt32(s.Value)));
            //                }
            //            }
            //            model.Feedbacks.Add(rf);
            //        }
            //    }
            //}

            return View(archive);
        }

        public ActionResult UploadPaper(int id, string type)
        {
            Archive archive = db.Archives.Find(id);
            //security check
            if (!Utility.IsUserAllowedtoOpenArchive(archive, Membership.GetUser()))
                return RedirectToAction("Proposals");


            if (archive.Status == 4 && (archive.PaperStatus < 2 || archive.PaperStatus > 5))
            {
                return View(archive);
            }
            else
                return RedirectToAction("Proposals");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}